/*
 * SortedDBFile.h
 *
 *  Created on: Mar 2, 2011
 *      Author: mayank
 */

#ifndef SORTEDDBFILE_H_
#define SORTEDDBFILE_H_

#include "TwoWayList.h"
#include "Record.h"
#include "Schema.h"
#include "File.h"
#include "Comparison.h"
#include "ComparisonEngine.h"
#include "BigQ.h"
#include "GenericDBFile.h"

#ifndef FTYPE_
#define FTYPE_
typedef enum {heap, sorted, tree} fType;
#endif

//class GenericDBFile;
#ifndef SORTINFO_
#define SORTINFO_
struct SortInfo {
	OrderMaker *myOrder;
	int runLength;
};
#endif

class SortedDBFile: public GenericDBFile{

private:

	BigQ *myBigQ;
	typedef enum {start, writing, reading} mode;
	mode currentMode;
	File* myFile;
	File* tempFile;
	//Make it if needed afterwards
	//void ExtractOrderMaker();
	void ChangeToWrite();
	void ChangeToRead();
	void AddToFile(Record &addme);
	OrderMaker *sortOrder;
	int runLength;
	void merge();
	int pagePointer;
	Page bufferPage;
	Page tempPage;
	void DumpRecordToFile(Record* addMe ,Page &currentPage,File *addTo);
	int GetRecordFromFile(Record* getMe, Page &currentPage, File* fromMe, int &pageNumber);
public:

	SortedDBFile();
	SortedDBFile(struct SortInfo* mySortInfo);
	~SortedDBFile();
	int Create (char *fpath);
	int Open (char *fpath);
	int Close ();

	void Load (Schema &myschema, char *loadpath);

	void MoveFirst ();
	void Add (Record &addme);
	int GetNext (Record &fetchme);
	int GetNext (Record &fetchme, CNF &cnf, Record &literal);

};

#endif /* SORTEDDBFILE_H_ */
